<?php
namespace yii\decline\rest;

use Yii;
use yii\decline\db\DBHelper;
use yii\decline\helpers\ArrayHelper;
use yii\decline\web\NoParamsException;

class PublicExt
{
    public static function actionDo($modelClass, $filter)
    {
        if (!$filter)
            $filter = Yii::$app->getRequest()->getBodyParams();
        if (!$filter) {
            return $modelClass::find()->count();
        } else {
            if (array_key_exists("handle", $filter)) {
                $handle = $filter["handle"];
                unset($filter["handle"]);
            } else {
                throw new NoParamsException('缺少参数!');
            }
            $alias = ArrayHelper::remove($filter, 'alias', '');
            $key = key($handle);
            if ($handle[$key]) {
                $data = DBHelper::Search($modelClass::find()->from($modelClass::tableName() . " {$alias}"), $filter)->asArray()->$key($handle[$key]);
            } else {
                $data = DBHelper::Search($modelClass::find()->from($modelClass::tableName() . " {$alias}"), $filter)->asArray()->$key();
            }
            if (method_exists($modelClass, 'after_public')) {
                $class = yii\decline\helpers\ArrayHelper::remove($filter, 'after');
                list($status, $data) = $modelClass->after_public($data, $class);
                if ($status >= $modelClass::ACTION_RETURN) {
                    return $data;
                }
            }
            return $data;
        }
    }
}